import { defIDeclareGoodsTemp, defEDeclareGoodsTemp } from '@/api/downloadTemp'
import { evenRound } from '@/libs/tools'

export default {
    data () {
        return {
            CommInfoDataList: []
        }
    },
    methods: {
        initGoodsList (data) {
            const _goodsKey = new Date().getTime()
            data.forEach((item, i) => {
                item._key = _goodsKey + i // 设置商品在前端中的主键
                item.goodsIndex = i + 1 // 重新设置商品序号避免删除数据后没有整体保存商品数据导致从而导致商品序号不连贯
            })
            this.CommInfoDataList = data.slice()
            this.currentSelectGoodsId = ''
            this.isInsertGoods = 0
            this._goodsSelection = []
        },
        // 清除错误校验信息
        clearGoodsErrById (id, errors = null) {
            if (id && this.goodsErrDataList && this.goodsErrDataList[id]) {
                let noErr = true
                if (errors) {
                    const keys = Object.keys(this.goodsErrDataList[id])
                    keys.forEach(k => {
                        if (errors[k]) {
                            noErr = false
                        } else {
                            delete this.goodsErrDataList[id][k]
                        }
                    })
                }
                if (noErr) {
                    this.goodsErrDataList[id] = null
                }
            }
        },
        focusGoodsForm () {
            const manualNo = this.getFormByKey('declareForm', 'manualNo')
            const target = manualNo
                ? 'contrItem'
                : 'codeTs'
            this.setAssignFocus('goodsForm', target)
        },
        // 单击商品
        getComDetails (data) {
            this._goodsKey = data._key // 缓存商品的唯一标识
            this.currentSelectGoodsId = data.goodsIndex
            this.SelCommInfoChange(data)
            this.focusGoodsForm()
            this.$nextTick(() => {
                this.clearFormTips('goodsForm')
                const id = data.declareGoodsId
                if (id && this.goodsErrDataList && this.goodsErrDataList[id]) {
                    const err = this.goodsErrDataList[id]
                    this.setFormTips('goodsForm', err)
                }
            })
        },
        // 赋值商品
        SelCommInfoChange (data) {
            this.setFormData('goodsForm', data)
        },
        // 重置商品表单
        refreshGoodsInfo () {
            this._goodsKey = '' // 重置商品的唯一标识
            this.resetForm('goodsForm')
            const len = this.CommInfoDataList.length
            let data = {
                goodsIndex: len + 1
            }
            this.SelCommInfoChange(data)
        },
        // 复制单行商品
        handleCopyGoods () {
            if (!this.currentSelectGoodsId) {
                this.$Message.warning('请选择需要复制的商品')
                return
            }
            let data = this.CommInfoDataList[this.currentSelectGoodsId - 1]
            if (data) {
                data = JSON.parse(JSON.stringify(data))
                data.goodsIndex = this.CommInfoDataList.length + 1
                const keys = ['declareGoodsId', 'goodsLimitId', 'invtCkGoodsId', 'invtGcGoodsId']
                keys.forEach(k => {
                    data[k] = ''
                })
                if (data.customsGoodsLimitNewVos && data.customsGoodsLimitNewVos.length > 0) {
                    data.customsGoodsLimitNewVos.forEach(item => {
                        item.createTime = ''
                        item.declareGoodsId = ''
                        item.goodsLimitId = ''
                        item.modifyTime = ''

                        if (item.customsGoodsLimitVins && item.customsGoodsLimitVins.length > 0) {
                            item.customsGoodsLimitVins.forEach(subItem => {
                                subItem.goodsLimitId = ''
                                subItem.goodsLimitVinId = ''
                                subItem.createTime = ''
                                subItem.modifyTime = ''
                            })
                        }
                    })
                }
                data._key = new Date().getTime() // 获取商品信息唯一标识 新增的商品需要重新设置
                this.saveGoods(data)
                this.refreshGoodsInfo()
                this.focusGoodsForm()
            }
        },
        // 插入商品数据
        handleInsertGoods () {
            if (this.currentSelectGoodsId) {
                this.handleAddGoods()
                this.isInsertGoods = 1
                this.setFormData('goodsForm', 'goodsIndex', this.currentSelectGoodsId)
            } else {
                this.$Message.warning('请先选择一条商品数据')
            }
        },
        // 新增商品
        handleAddGoods () {
            // 设置光标
            this.focusGoodsForm()
            // 清空选择的内容
            this.refreshGoodsInfo()
        },
        // 删除商品
        delGoodsInfo () {
            if (!this._goodsSelection || !this._goodsSelection.length) {
                this.$Message.warning('请勾选需要删除的商品明细')
                return false
            }
            this.$Modal.confirm({
                title: '删除商品明细',
                content: '删除商品明细,数据无法恢复,是否确认删除？',
                onOk: () => {
                    const list = this.CommInfoDataList.filter(item => {
                        return this._goodsSelection.indexOf(item._key) < 0
                    })
                    list.forEach((item, index) => {
                        item.goodsIndex = index + 1
                    })
                    this.CommInfoDataList = list
                    this.$Message.success('商品明细删除成功！')
                    this.refreshGoodsInfo()
                    this.currentSelectGoodsId = ''
                    this.isInsertGoods = 0
                    this._goodsSelection = []
                }
            })
        },
        // 上移
        handleUpGoods () {
            if (!this.currentSelectGoodsId) {
                this.$Message.warning('请选择需要上移的商品明细')
                return false
            }
            let index = this.currentSelectGoodsId - 1
            if (this.currentSelectGoodsId === 0 || index === 0) {
                this.$Message.warning('已经是到顶了，不能在上移了！')
                return false
            }
            let start = this.CommInfoDataList[index]
            let end = this.CommInfoDataList[index - 1]
            start.goodsIndex--
            end.goodsIndex++
            this.CommInfoDataList.splice(index - 1, 2, start, end)
            this.currentSelectGoodsId = this.currentSelectGoodsId - 1
            this.moveGoodsSuccess()
        },
        // 下移
        handleDownGoods () {
            if (!this.currentSelectGoodsId) {
                this.$Message.warning('请选择需要下移的商品明细')
                return false
            }
            let maxIndex = this.CommInfoDataList.length - 1
            let index = this.currentSelectGoodsId - 1
            if (index === maxIndex) {
                this.$Message.warning('已经是到底了，不能在下移了！')
                return false
            }
            let start = this.CommInfoDataList[index + 1]
            let end = this.CommInfoDataList[index]
            start.goodsIndex--
            end.goodsIndex++
            this.CommInfoDataList.splice(index, 2, start, end)
            this.currentSelectGoodsId = this.currentSelectGoodsId + 1
            this.moveGoodsSuccess()
        },
        moveGoodsSuccess () {
            this.setFormData('goodsForm', 'goodsIndex', this.currentSelectGoodsId) // 更新商品序号(!important)
        },
        // 商品表单多选
        handleGoodsSelectionChange (list) {
            this._goodsSelection = list.map(item => item._key)
        },
        // 校验保存的商品信息
        checkGoodsData (data) {
            let rules = {
                codeTs (v) {
                    return v ? '' : '商品编号不能为空'
                },
                goodsName (v) {
                    return v ? '' : '商品名称不能为空'
                },
                gqty (v) {
                    return Number(v) < 0 ? '成交数量不能小于0' : ''
                }
            }
            let err = ''
            let key = Object.keys(rules).find(k => {
                err = rules[k].call(this, data[k])
                return err
            })
            return {
                key,
                err
            }
        },
        // 获取需要保存的商品数据
        getGoodsData (data) {
            let params = JSON.parse(JSON.stringify(data))
            // 清空无效的版本号
            if (isNaN(Number(params.exgVersion))) params.exgVersion = ''
            // 格式化 数量 价格
            if (params.gqty) {
                const gqty = Number(params.gqty)
                params.gqty = isNaN(gqty) ? '' : evenRound(gqty, 5)
            }
            if (params.declPrice) {
                const declPrice = Number(params.declPrice)
                params.declPrice = isNaN(declPrice) ? '' : evenRound(declPrice, 4)
            }
            if (params.declTotal) {
                const declTotal = Number(params.declTotal)
                params.declTotal = isNaN(declTotal) ? '' : evenRound(declTotal, 2)
            }
            if (params.firstQty) {
                const firstQty = Number(params.firstQty)
                params.firstQty = isNaN(firstQty) ? '' : evenRound(firstQty, 5)
            }
            if (params.secondUnit) {
                if (params.secondQty) {
                    const secondQty = Number(params.secondQty)
                    params.secondQty = isNaN(secondQty) ? '' : evenRound(secondQty, 5)
                }
            } else {
                params.secondQty = ''
            }
            if (!Array.isArray(params.customsGoodsLimitNewVos)) {
                params.customsGoodsLimitNewVos = []
            }
            params._key = this._goodsKey || new Date().getTime() // 获取商品信息唯一标识 新增的商品需要重新设置

            return params
        },
        // 保存商品信息
        saveGoodsData (obj) {
            // 保存前校验商品部分字段是否符合规范
            let { err, key } = this.checkGoodsData(obj)
            if (err) {
                this.setAssignFocus('goodsForm', key) // 光标选中对应的输入框
                this.$Message.warning(err)
                return null
            }
            let data = this.getGoodsData(obj)
            if (data) {
                this.saveGoods(data)
                this.refreshGoodsInfo()
                this.focusGoodsForm()
            }
        },
        // 保存商品
        saveGoods (data) {
            const len = this.CommInfoDataList.length
            data.goodsIndex = data.goodsIndex === '' ? (len + 1) : data.goodsIndex
            const index = data.goodsIndex
            // 新增
            if (index > len) {
                this.CommInfoDataList.push(data)
            } else {
                if (this.isInsertGoods) {
                    // 插入操作
                    this.CommInfoDataList.splice(index - 1, 0, data)
                    this.CommInfoDataList.forEach((item, i) => {
                        item.goodsIndex = i + 1
                    })
                    this.currentSelectGoodsId++
                } else {
                    // 编辑操作
                    this.CommInfoDataList.splice(index - 1, 1, data)
                    this.currentSelectGoodsId = 0
                }
            }
            this.clearGoodsErrById(data.declareGoodsId, this.getFormTips('goodsForm'))
        },
        // 导入商品信息
        importGoods () {
            if (!this.form.declareId) {
                this.$Message.warning('请先暂存')
                return false
            }
            const downLoadUrl = this.isImport ? defIDeclareGoodsTemp : defEDeclareGoodsTemp
            this.modalParams.declareInfoImportParams = {
                title: '导入商品信息',
                subTitle: '准备商品信息',
                hintTxt: '使用数据模板文件，录入商品信息。为了保证成功，请根据表格中批注的数据格式并按照字段顺序进行录入。一次最多导入1000条。',
                actionUrl: '/ui/declaremanager/declareGoods/importCustomsDeclareGoodsByExcel',
                downLoadUrl,
                type: this.form.businessType,
                declareId: this.form.declareId,
                importType: 'goods'
            }
            this.modalParams.declareInfoImportShow = true
        },
        importGoodsSuccess (resData) {
            const list = this.CommInfoDataList.slice()
            this.initGoodsList(list)
        }
    }
}
